import React from 'react';
import MDDRenderEngine, { JSONWatch } from '@cniot/mdd-render-engine';
import schema from './mdd.schema.json';

export default function (props) {
  const { params, extendsModule, closeSelf, parentRefresh, schema: _schema } = props;
  const { isParentRefresh } = _schema || {};
  // 刷新父页面
  const onReady = React.useCallback((engine) => {
    engine.on('form:finish', () => {
      closeSelf && closeSelf();
      if (isParentRefresh) {
        parentRefresh();
      }
    });
  }, []);

  return (
    <MDDRenderEngine
      schema={schema}
      modules={createModules({ params, extendsModule })}
      onReady={onReady}
    ></MDDRenderEngine>
  );
}

/**
 * 如果是弹窗，需要初始化 $PARAMS 模块用于传值
 */
function createModules({ params = {}, extendsModule = {} }) {
  return React.useState(() => {
    return new Map([
      ['$PARAMS', new JSONWatch(params)],
      ['$EXTENDS_MODULE', extendsModule],
    ]);
  })[0];
}
